package com.chenyi.file.utils;

import com.alibaba.fastjson.JSON;
import com.chenyi.file.config.FileQiniuConfig;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件 七牛云 上传
 */
public class FileQiniuUtils {

    private static final String HUAD = "华东";

    private static final String HUAB = "华北";

    private static final String HUAN = "华南";

    private static final String BEIM = "北美";

    /**
     * 简单上传
     * @param key
     * @param bytes
     * @return
     */
    public static String uplaodSimple(String key, byte[] bytes) throws Exception {
        Configuration cfg = new Configuration(getRegion(FileQiniuConfig.getRegion()));
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(FileQiniuConfig.getAccessKey(), FileQiniuConfig.getSecretKey());
        String upToken = auth.uploadToken(FileQiniuConfig.getBucket());
        Response response = uploadManager.put(bytes, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        return FileQiniuConfig.getHost() +"/"+ putRet.key;
    }

    /**
     * 简单上传
     * @param key
     * @param file
     * @return
     */
    public static String uplaodSimple(String key, File file) throws Exception {
        Configuration cfg = new Configuration(getRegion(FileQiniuConfig.getRegion()));
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(FileQiniuConfig.getAccessKey(), FileQiniuConfig.getSecretKey());
        String upToken = auth.uploadToken(FileQiniuConfig.getBucket());
        Response response = uploadManager.put(file, key, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
        return FileQiniuConfig.getHost() +"/"+ putRet.key;
    }

    /**
     * 得到机房的对应关系
     * @param zone 机房名称
     * @return Region
     */
    private static Region getRegion(String zone){

        if(HUAD.equals(zone)){
            return Region.huadong();
        } else if(HUAB.equals(zone)){
            return Region.huabei();
        } else if(HUAN.equals(zone)){
            return Region.huanan();
        } else if (BEIM.equals(zone)){
            return Region.beimei();
            // 否则就是东南亚
        } else {
            return Region.qvmHuadong();
        }
    }

}
